<?php
namespace App\Models;

use App\Exceptions\ApiErrorException;
use App\Exceptions\ApiException;
use App\Util\ArrayUtil;


/**
 * 商品售卖SKU模型
 * Class GoodsSku
 * @package app\model
 */
class GoodsSku extends BaseModel
{
    const KEY = 'id';
    const TABLE = 'sp_goods_sku';

    protected $table = self::TABLE;
    protected $primaryKey = self::KEY;
    protected $connection = 'mysql';

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';

    protected $guarded = [];

    protected $casts = [
        'create_time' => 'datetime:Y-m-d H:i:s',
        'update_time' => 'datetime:Y-m-d H:i:s',
    ];

    /**
     * 获取器：规格值ID集
     * @param $value
     * @return array|mixed
     */
    public function getSpecValueIdsAttribute($value)
    {
        return ArrayUtil::jsonDecode($value);
    }

    /**
     * 获取器：规格属性
     * @param $value
     */
    public function getGoodsPropsAttribute($value)
    {
        return ArrayUtil::jsonDecode($value);
    }

    /**
     * 获取sku信息详情
     * @param int $goodsId
     * @param string $goodsSkuId
     * @return static|array|null
     */
    public static function detail(int $goodsId, string $goodsSkuId)
    {
        return static::get(['goods_id' => $goodsId, 'goods_sku_id' => $goodsSkuId], ['image']);
    }

    /**
     * 获取商品SKU列表
     * @param int $goodsId 商品ID
     * @param bool $withImage 是否携带sku封面图
     */
    public static function getSkuList(int $goodsId, bool $withImage = false)
    {
        return (new static)->with($withImage ? ['image'] : [])
            ->where('goods_id', '=', $goodsId)
            ->get();
    }

    /**
     * 生成skuList数据(写入goods_sku_id)
     * @param array $newSpecList
     * @param array $skuList
     * @return array
     */
    public static function getNewSkuList(array $newSpecList, array $skuList): array
    {
        foreach ($skuList as &$skuItem) {
            $skuItem['specValueIds'] = static::getSpecValueIds($newSpecList, $skuItem['skuKeys']);
            $skuItem['goodsProps'] = static::getGoodsProps($newSpecList, $skuItem['skuKeys']);
            $skuItem['goods_sku_id'] = implode('_', $skuItem['specValueIds']);
        }
        return $skuList;
    }

    /**
     * 根据$skuKeys生成规格值id集
     * @param array $newSpecList
     * @param array $skuKeys
     * @return array
     */
    private static function getSpecValueIds(array $newSpecList, array $skuKeys): array
    {
        $goodsSkuIdArr = [];
        foreach ($skuKeys as $skuKey) {
            $groupItem = ArrayUtil::arraySearch($newSpecList, 'key', $skuKey['groupKey']);
            $specValueItem = ArrayUtil::arraySearch($groupItem['valueList'], 'key', $skuKey['valueKey']);
            $goodsSkuIdArr[] = $specValueItem['spec_value_id'];
        }
        return $goodsSkuIdArr;
    }

    /**
     * 根据$skuKeys生成规格属性记录
     * @param array $newSpecList
     * @param array $skuKeys
     * @return array
     */
    private static function getGoodsProps(array $newSpecList, array $skuKeys): array
    {
        $goodsPropsArr = [];
        foreach ($skuKeys as $skuKey) {
            $groupItem = ArrayUtil::arraySearch($newSpecList, 'key', $skuKey['groupKey']);
            $specValueItem = ArrayUtil::arraySearch($groupItem['valueList'], 'key', $skuKey['valueKey']);
            $goodsPropsArr[] = [
                'group' => ['name' => $groupItem['spec_name'], 'id' => $groupItem['spec_id'],'groupKey' => $skuKey['groupKey']],
                'value' => ['name' => $specValueItem['spec_value'], 'id' => $specValueItem['spec_value_id'],'key' =>$skuKey['valueKey']]
            ];
        }
        return $goodsPropsArr;
    }

    /**
     * 新增商品sku记录
     * @param int $goodsId
     * @param array $newSkuList
     * @param int $specType
     * @return array|bool|false
     */
    public static function add(int $goodsId,  array $skuList = [])
    {
        // 单规格模式
        $dataset = [];
        foreach ($skuList as $skuItem) {
            $dataset[] =  [
                'off_sale' => $skuItem['off_sale']??0,
                'goods_sku_id' => $skuItem['goods_sku_id'],
                'goods_price' => $skuItem['goods_price'] ?: 0.01,
                'line_price' => $skuItem['line_price'] ?: 0.00,
                'goods_sku_no' => $skuItem['goods_sku_no'] ?: '',
                'stock_num' => $skuItem['stock_num'] ?: 0,
                'goods_props' => json_encode($skuItem['goodsProps']),
                'spec_value_ids' => json_encode($skuItem['specValueIds']),
                'goods_id' => $goodsId,
                'create_time' =>date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
            ];
        }
        return (new static)->insert($dataset);
    }


    public static function edit(int $goodsId, array $skuList = [])
    {
        // 删除所有的sku记录
        static::query()->where('goods_id',$goodsId)->delete();
        // 新增商品sku记录
        return static::add($goodsId,  $skuList);
    }

    /**
     * 获取库存总数量 (根据sku列表数据)
     * @param array $skuList
     * @return float|int
     */
    public static function getStockTotal(array $skuList)
    {
        return (int)ArrayUtil::getArrayColumnSum($skuList, 'stock_num');
    }

    /**
     * 获取商品价格高低区间 (根据sku列表数据)
     * @param array $skuList
     * @return array
     */
    public static function getGoodsPrices(array $skuList): array
    {
        $goodsPriceArr = ArrayUtil::getArrayColumn($skuList, 'goods_price');
        return empty($goodsPriceArr) ? [0, 0] : [min($goodsPriceArr), max($goodsPriceArr)];
    }

    /**
     * 获取划线价格高低区间 (根据sku列表数据)
     * @param array $skuList
     * @return array
     */
    public static function getLinePrices(array $skuList): array
    {
        $linePriceArr = ArrayUtil::getArrayColumn($skuList, 'line_price');
        return empty($linePriceArr) ? [0, 0] : [min($linePriceArr), max($linePriceArr)];
    }
}
